/*
验证器
验证传入的数据和图片是否符合规范
*/

package validator

import (
    "fmt"
    "reflect"
    "strings"

    "gitee.com/keeving/quanta-test-cat/utils/errmsg"
    "github.com/go-playground/locales/zh_Hans_CN"
    unTrans "github.com/go-playground/universal-translator"
    "github.com/go-playground/validator/v10"
    zhTrans "github.com/go-playground/validator/v10/translations/zh"
)

// Validate 数据验证模块
func Validate(data any) (string, int) {
    validate := validator.New()
    uni := unTrans.New(zh_Hans_CN.New())
    trans, _ := uni.GetTranslator("zh_Hans_CN")

    err := zhTrans.RegisterDefaultTranslations(validate, trans)
    if err != nil {
        fmt.Println("err:", err)
    }
    validate.RegisterTagNameFunc(func(field reflect.StructField) string {
        label := field.Tag.Get("label")
        return label
    })

    err = validate.Struct(data)
    if err != nil {
        for _, v := range err.(validator.ValidationErrors) {
            return v.Translate(trans), errmsg.ERROR
        }
    }
    return "", errmsg.SUCCESS
}

// 图片文件验证模块
// IsImage 检查文件的 MIME 类型是否为图片
func IsImage(mimeType string) bool {
    // 图片的 MIME 类型前缀
    imagePrefix := "image/"

    // 检查 MIME 类型是否以 "image/" 开头
    return strings.HasPrefix(mimeType, imagePrefix)
}
